#include "AgentCore.h"
#include <random>
#include <cmath>

// Random number generator
static std::mt19937 gen(std::random_device{}());
static std::uniform_real_distribution<> dis(0.0, 1.0);

EconomicAgent* createAgents(int count, AgentType type) {
    EconomicAgent* agents = new EconomicAgent[count];
    for (int i = 0; i < count; ++i) {
        agents[i].id = i;
        agents[i].type = type;
        agents[i].wealth = dis(gen) * 10000;
        
        switch(type) {
            case CONSUMER:
                agents[i].consumption = dis(gen) * 5000;
                agents[i].production = 0;
                break;
            case PRODUCER:
                agents[i].consumption = 0;
                agents[i].production = dis(gen) * 10000;
                break;
            case INVESTOR:
                agents[i].consumption = dis(gen) * 2000;
                agents[i].production = 0;
                break;
            case GOVERNMENT:
                agents[i].consumption = dis(gen) * 10000;
                agents[i].production = 0;
                break;
        }
    }
    return agents;
}

void simulateAgentBehavior(EconomicAgent* agents, int count, const MarketConditions* market) {
    for (int i = 0; i < count; ++i) {
        // Simple behavioral rules based on market conditions
        double adjustment = 1.0 + (dis(gen) - 0.5) * 0.1;
        
        switch(agents[i].type) {
            case CONSUMER:
                agents[i].consumption *= adjustment * (1.0 - market->inflationRate * 0.5);
                break;
            case PRODUCER:
                agents[i].production *= adjustment * (1.0 + market->priceLevel * 0.1);
                break;
            case INVESTOR:
                agents[i].wealth *= 1.0 + (market->interestRate * 0.8 + (dis(gen) - 0.5) * 0.05);
                break;
            case GOVERNMENT:
                agents[i].consumption *= 1.0 + (market->inflationRate * 0.2);
                break;
        }
    }
}

void runMarketSimulation(int cycles, EconomicAgent* consumers, int consumerCount,
                        EconomicAgent* producers, int producerCount,
                        MarketConditions* market) {
    for (int cycle = 0; cycle < cycles; ++cycle) {
        // Update market conditions
        market->priceLevel *= 1.0 + (dis(gen) - 0.45) * 0.05;
        market->inflationRate = (market->priceLevel - 1.0) * 0.8;
        market->interestRate = 0.02 + market->inflationRate * 0.5;
        
        // Simulate agent behaviors
        simulateAgentBehavior(consumers, consumerCount, market);
        simulateAgentBehavior(producers, producerCount, market);
    }
}

void freeAgents(EconomicAgent* agents) {
    delete[] agents;
}